package com.yh.csx.crm.service;

import com.github.pagehelper.PageHelper;
import com.yh.b2b.usercenter.facade.stub.vo.UserVO;
import com.yh.csx.crm.core.enums.PermissionTypeEnum;
import com.yh.csx.crm.core.enums.PositionEnum;
import com.yh.csx.crm.core.exception.BusinessException;
import com.yh.csx.crm.dao.CustomerMapper;
import com.yh.csx.crm.dao.SysOrganizationMapper;
import com.yh.csx.crm.dao.SysSalesPermissionMapper;
import com.yh.csx.crm.po.SysOrganization;
import com.yh.csx.crm.po.SysSalesPermission;
import com.yh.csx.crm.qo.OrganizationQo;
import com.yh.csx.crm.qo.SalesQo;
import com.yh.csx.crm.service.logic.PermissionLogic;
import com.yh.csx.crm.service.logic.UserLogic;
import com.yh.csx.crm.vo.PermissionVo;
import com.yh.csx.crm.vo.SalesInfoVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 * @author Huang Zhaoping
 * @date 2019/3/1
 */
@Service
public class SaleService {

    @Autowired
    private SysSalesPermissionMapper salesPermissionMapper;

    @Autowired
    private SysOrganizationMapper organizationMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private UserLogic userLogic;

    @Autowired
    private PermissionLogic permissionLogic;


    public SysSalesPermission findSalesPermission(Long userId) {
        return salesPermissionMapper.findByUserId(userId);
    }

    public SysSalesPermission findSalesPermission(String mobile) {
        return salesPermissionMapper.findByMobile(mobile);
    }

    public List<SalesInfoVo> findSalesList(SalesQo qo) {
        if (qo.isPageable()) {
            PageHelper.startPage(qo.getPageNum(), qo.getPageSize(), qo.isCount());
        }
        return salesPermissionMapper.selectSalesInfoList(qo);
    }

    public SysSalesPermission findSalesByWorkNumber(String workNumber) {
        SalesQo qo = new SalesQo();
        qo.setWorkNumber(workNumber);
        List<SysSalesPermission> list = salesPermissionMapper.selectSalesList(qo);
        return list.isEmpty() ? null : list.get(0);
    }

    private void validateSales(SysSalesPermission sales) {
        if (sales.getParid() == null) sales.setParid(0L);
        if (StringUtils.isBlank(sales.getWorkNumber())) throw new BusinessException("工号不能为空");
        if (StringUtils.isBlank(sales.getPhone())) throw new BusinessException("手机号码不能为空");
        if (!Pattern.matches("\\d{11}", sales.getPhone())) throw new BusinessException("手机号码格式错误");
        if (StringUtils.isBlank(sales.getUserName())) throw new BusinessException("用户姓名不能为空");
        if (StringUtils.isBlank(sales.getPosition())) throw new BusinessException("请选择用户的职位");
        try {
            PositionEnum.valueOf(sales.getPosition());
        } catch (Exception e) {
            throw new BusinessException("职位类型无效");
        }
        if (sales.getPermissionType() == null) throw new BusinessException("请选择数据权限");
        Integer type = sales.getPermissionType();
        if (type == null) throw new BusinessException("数据权限不能为空");
        if (type == PermissionTypeEnum.SPEC_ORG.getCode()) {
            if (StringUtils.isBlank(sales.getRelatedOrgs())) {
                throw new BusinessException("请选择指定部门");
            }
        } else {
            sales.setRelatedOrgs("");
        }
    }

    private void validateOrganization(SysSalesPermission sales) {
        if (sales.getOrgId() == null) throw new BusinessException("请选择所属部门");
        SysOrganization org = organizationMapper.selectByPrimaryKey(sales.getOrgId());
        if (org == null) throw new BusinessException("所属部门不存在");
        OrganizationQo qo = new OrganizationQo();
        qo.setParentId(org.getId());
        if (organizationMapper.selectOrganizationCount(qo) > 0) {
            throw new BusinessException("不能将用户归属于包含下级的部门");
        }
    }

    @Transactional
    public void createSales(SysSalesPermission sales) {
        validateSales(sales);
        validateOrganization(sales);
        if (findSalesPermission(sales.getPhone()) != null) {
            throw new BusinessException("手机号码已经注册");
        }
        if (findSalesByWorkNumber(sales.getWorkNumber()) != null) {
            throw new BusinessException("工号已经存在");
        }
        String parentPath = null;
        if (sales.getParid() != 0) {
            SysSalesPermission parent = salesPermissionMapper.findByUserId(sales.getParid());
            if (parent == null) throw new BusinessException("所属领导不存在");
            parentPath = parent.getPath();
        }
        Long userId = userLogic.findUserId(sales.getPhone());
        if (userId == null) {
            userId = userLogic.registerUser(sales.getPhone(), sales.getUserName());
        } else {
            SysSalesPermission exists = findSalesPermission(userId);
            if (exists != null) {
                throw new BusinessException("手机号码已经注册");
            }
            if (StringUtils.isBlank(sales.getWorkNumber())) {
                UserVO userVO = userLogic.getUserById(userId);
                if (StringUtils.isNotBlank(userVO.getUserNumber())) {
                    sales.setWorkNumber(userVO.getUserNumber());
                }
            }
        }
        sales.setUserId(userId);
        sales.setPath(StringUtils.isBlank(parentPath) ? String.valueOf(sales.getUserId()) : (parentPath + "," + userId));
        salesPermissionMapper.insertSelective(sales);
    }

    @Transactional
    public void updateSales(SysSalesPermission sales) {
        SysSalesPermission exists = salesPermissionMapper.selectByPrimaryKey(sales.getId());
        if (exists == null) throw new BusinessException("用户不存在");
        validateSales(sales);
        String oldPath = exists.getPath();
        if (!Objects.equals(sales.getParid(), exists.getParid())) {
            if (Objects.equals(sales.getParid(), exists.getUserId())) {
                throw new BusinessException("请勿将自己指定为自己的所属领导");
            }
            if (sales.getParid() == 0) {
                exists.setPath(String.valueOf(exists.getUserId()));
            } else {
                SysSalesPermission parent = salesPermissionMapper.findByUserId(sales.getParid());
                if (parent == null) throw new BusinessException("所属领导不存在");
                exists.setPath(parent.getPath() + "," + exists.getUserId());
            }
            exists.setParid(sales.getParid());
        }
        if (!Objects.equals(sales.getWorkNumber(), exists.getWorkNumber())) {
            if (findSalesByWorkNumber(sales.getWorkNumber()) != null) {
                throw new BusinessException("工号已经存在");
            }
            exists.setWorkNumber(sales.getWorkNumber());
        }
        if (!Objects.equals(sales.getPhone(), exists.getPhone())) {
            if (findSalesPermission(sales.getPhone()) != null) {
                throw new BusinessException("手机号码已经存在");
            }
            exists.setPhone(sales.getPhone());
        }
        if (!Objects.equals(sales.getOrgId(), exists.getOrgId())) {
            validateOrganization(sales);
            exists.setOrgId(sales.getOrgId());
        }
        exists.setUserName(sales.getUserName());
        exists.setPosition(sales.getPosition());
        exists.setPermissionType(sales.getPermissionType());
        exists.setRelatedOrgs(sales.getRelatedOrgs());
        exists.setUpdateBy(sales.getUpdateBy());
        salesPermissionMapper.updateByPrimaryKeySelective(exists);
        if (!StringUtils.equals(oldPath, exists.getPath())) {
            salesPermissionMapper.updateChildPath(oldPath, exists.getPath());
        }
    }

    public void deleteSales(Integer salesId) {
        SysSalesPermission sales = salesPermissionMapper.selectByPrimaryKey(salesId);
        if (sales == null) throw new BusinessException("用户不存在");
        if (customerMapper.countBySalesUserId(sales.getUserId()) > 0) {
            throw new BusinessException("请先移交该用户的客户");
        }
        SalesQo qo = new SalesQo();
        qo.setParentId(sales.getUserId());
        if (salesPermissionMapper.selectSalesCount(qo) > 0) {
            throw new BusinessException("请先清除该用户的下属用户");
        }
        salesPermissionMapper.deleteByPrimaryKey(salesId);
    }


    public List<Long> getPermitUserIds(Long userId) {
        PermissionVo vo = permissionLogic.getPermissionByUserId(userId);
        return vo.getUserIds();
    }

    public List<String> getPermitCusCodes(Long userId) {
        PermissionVo vo = permissionLogic.getPermissionByUserId(userId);
        return permissionLogic.getPermitCusCodes(vo);
    }

    public List<String> getPermitProvinceCodes(Long userId) {
        PermissionVo vo = permissionLogic.getPermissionByUserId(userId);
        return permissionLogic.getPermitProvinceCodes(vo);
    }

}
